package com.example.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.commonutils.ResultData;
import com.example.order.entity.Order;
import com.example.order.service.OrderService;
import com.example.order.service.PayLogService;
import com.example.servicebase.client.EduClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-06-05
 */
@RestController
@RequestMapping("/eduorder/paylog")
public class PayLogController {
    @Autowired
    private PayLogService payLogService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private EduClient client;

    //根据订单号，生成微信支付的二维码
    @GetMapping(value = "createNative/{orderNo}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData createNative(@PathVariable String orderNo) {
        Map map = payLogService.createNative(orderNo);
        return ResultData.ok().data(map);
    }

    @GetMapping(value = "getOrderInfo/{orderNo}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ResultData getOrderInfo(@PathVariable String orderNo) {
        //调用查询接口
        Map<String, String> map = payLogService.queryPayStatus(orderNo);
        if (map == null) {//出错
            return ResultData.error().message("支付出错");
        }
        if (map.get("trade_state").equals("SUCCESS")) {//如果成功
            //将对应的订单信息查出来
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(wrapper);
            String courseId = order.getCourseId();
            client.buyCount(courseId);
            //将对应课程的购买数+1

            //更改订单状态
            payLogService.updateOrderStatus(map);
            return ResultData.ok().message("支付成功");
        }
        return ResultData.ok().code(25000).message("支付中");
    }
}

